<script lang="ts" setup>
import { message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import type { UnwrapRef } from 'vue';
import { useDownExcel } from '../useDownExcel';
import { useMonthHistoryStore } from '@/store/modules/dcp/assessment_indicators/month_history';

const loading = ref<boolean>(false);

const allColumns: any = [
  {
    title: '序号',
    dataIndex: 'sequenceNumber',
    key: 'sequenceNumber',
    width: '5%',
    align: 'center',
  },
  {
    title: '简称',
    dataIndex: 'abbreviation',
    key: 'abbreviation',
    width: '8%',
    align: 'center',
  },
  {
    title: '部门',
    dataIndex: 'departmentName',
    key: 'departmentName',
    width: '12%',
    align: 'center',
  },
  {
    title: '公共KPI指标（30分）',
    dataIndex: 'publicKpiScore',
    key: 'publicKpiScore',
    width: '10%',
    align: 'center',
  },
  {
    title: '职能工作考核（30分）',
    dataIndex: 'functionalWorkScore',
    key: 'functionalWorkScore',
    width: '10%',
    align: 'center',
  },
  {
    title: 'GS考核（30分）',
    dataIndex: 'gsScore',
    key: 'gsScore',
    width: '10%',
    align: 'center',
  },
  {
    title: '党支部堡垒指数考核',
    dataIndex: 'partyBranchIndex',
    key: 'partyBranchIndex',
    width: '10%',
    align: 'center',
  },
  {
    title: '倒三角支撑（10分）',
    dataIndex: 'reverseSupportScore',
    key: 'reverseSupportScore',
    width: '10%',
    align: 'center',
  },
  {
    title: '合计',
    dataIndex: 'totalScore',
    key: 'totalScore',
    width: '10%',
    align: 'center',
  },
  {
    title: '排名',
    dataIndex: 'ranking',
    key: 'ranking',
    width: '5%',
    align: 'center',
    fixed: 'right',
    sorter: (a: any, b: any) => Number(a.ranking) - Number(b.ranking),
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'lastColumn',
    width: '8%',
    align: 'center',
    fixed: 'right',
  },
];
const { auth } = useAuth();
function showRoleColumn() {
  return auth([
    'a_i_edit',
  ]);
}
const columns: any = computed(() => {
  return allColumns.filter((column: any) => {
    const flag = showRoleColumn();
    if (!flag && column.title === '操作') {
      return false;
    }
    return true;
  });
});
const dateList = ref<any[]>([]);
const activeKey = ref([]);
const key = ref<number>(0);
const month = ref<string>('');
// 获取月份
const yearMonth = ref<any[]>([]);
const monthHistoryStore = useMonthHistoryStore();
function getDateList() {
  yearMonth.value = monthHistoryStore.monthList;
  for (let i = 0; i < yearMonth.value.length; i++) {
    dateList.value.push({ header: yearMonth.value[i].yearMonth });
  }
}
// 根据月份获取数据
function convertDateStringToNumber(dateString: string) {
  const regex = /(\d{4})年(\d{2})月/;
  const matches = dateString.match(regex);
  if (matches) {
    const year = matches[1];
    const month = matches[2];
    const formattedDate = year + month;
    return Number.parseInt(formattedDate, 10);
  }
}
function onChange(keys: any) {
  key.value = keys;
  const date: any = convertDateStringToNumber(dateList.value[keys].header);
  month.value = date;
  getData(date);
}
const data = ref<AAPI.Month_Item[]>([]);
async function getData(yearMonth: any) {
  await getMonthDataByYearMonth(yearMonth).then((res: any) => {
    data.value = res.data;
  });
}
onMounted(async () => {
  await monthHistoryStore.getMonthList();
  getDateList();
});

// 编辑
const editableData: UnwrapRef<Record<string, any>> = reactive({});

function edit(id: number) {
  editableData[id] = cloneDeep(data?.value?.filter((item: AAPI.Month_Item) => id === item.sequenceNumber)[0]);
}

async function save(id: number) {
  const newData = Object.assign(data?.value?.filter((item: AAPI.Month_Item) => id === item.sequenceNumber)[0], editableData[id]);
  const updateDate = {
    sequenceNumber: newData.sequenceNumber,
    abbreviation: newData.abbreviation,
    departmentName: newData.departmentName,
    publicKpiScore: newData.publicKpiScore,
    functionalWorkScore: newData.functionalWorkScore,
    gsScore: newData.gsScore,
    partyBranchIndex: newData.partyBranchIndex,
    reverseSupportScore: newData.reverseSupportScore,
    totalScore: newData.totalScore,
    ranking: newData.ranking,
    yearMonth: convertDateStringToNumber(dateList.value[key.value].header),
  };
  await updateMonthDataByYearMonth(updateDate).then(() => {
    message.success('修改成功!');
    // 获取数据
    const date = convertDateStringToNumber(dateList.value[key.value].header);
    getData(date);
  });
  delete editableData[id];
}

function cancel(id: number) {
  delete editableData[id];
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            部门kpi-历史记录
          </div>
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-button type="primary" @click="$router.push('/assessment_indicators/kpi')">
            返回
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="content">
      <a-collapse v-model:activeKey="activeKey" accordion :bordered="false" class="m-collapse" @change="onChange">
        <a-collapse-panel v-for="(item, index) in dateList" :key="index" :header="item.header">
          <a-table
            :columns="columns" :data-source="data" row-key="id" :scroll="{ x: 1800 }" class="m-table"
            :loading="loading" :pagination="false"
          >
            <template #bodyCell="{ column, text, record }">
              <template
                v-if="['publicKpiScore', 'functionalWorkScore', 'gsScore', 'partyBranchIndex', 'reverseSupportScore'].includes(column.dataIndex as string)"
              >
                <div>
                  <a-input
                    v-if="editableData[record.sequenceNumber]"
                    v-model:value="editableData[record.sequenceNumber][column.dataIndex as string]"
                    style="margin: -5px 0;"
                  />
                  <template v-else>
                    {{ text }}
                  </template>
                </div>
              </template>
              <template v-if="column.dataIndex === 'departmentName'">
                {{ text }}
                <!-- <RouterLink :to="linkObject(record)">
              {{ text }}
            </RouterLink> -->
              </template>
              <template v-if="column.dataIndex === 'operation'">
                <div class="editable-row-operations">
                  <span v-if="editableData[record.sequenceNumber]">
                    <a-typography-link @click="save(record.sequenceNumber)">保存</a-typography-link>
                    <a @click="cancel(record.sequenceNumber)">取消</a>
                  </span>
                  <span v-else>
                    <a-space>
                      <a @click="edit(record.sequenceNumber)">编辑</a>
                    </a-space>
                  </span>
                </div>
              </template>
            </template>
          </a-table>
          <template #extra>
            <a-button v-if="month" type="link" @click="useDownExcel().downYunwanghistoryexcel(month)">
              导出
            </a-button>
          </template>
        </a-collapse-panel>
      </a-collapse>
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 31px;
    margin-bottom: 10px;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    height: 100%;
    overflow: auto;

    .m-collapse {
      max-height: 460px;
      overflow-y: auto;
    }
  }
}

.editable-row-operations a {
  margin-right: 8px;
}
</style>
